<template>
  <div class="place-order-wrapper"  v-loading="loading">
    <!-- 收货信息 -->
    <div class="receive-goods-info">
      <div class="receive-goods-title">
        收货信息
      </div>
      <div class="receive-goods-ipt">
        <div class="ipt-item">
          <div class="left">联系人 :</div>
          <input class="right" type="text" placeholder="请输入姓名" v-model="username">
        </div>
        <div class="ipt-item">
          <div class="left">手机号码 :</div>
          <input class="right" type="text" placeholder="请输入手机号码" v-model="usermobile">
        </div>
        <div class="ipt-upload">
          <div class="left">请上传收货人信息表 :</div>
          <div class="upload">
            <el-upload
              :action="fileAddress"
              :limit="1"
              :before-upload="beforeFileUpload"
              :on-remove="handleRemove"
              :file-list="fileList"
              :headers="headers"
              :on-success="uploadFileSuccess"
            >
            <!-- </el-upload> -->
              <el-button size="small" type="primary">上传文件</el-button>
              <i class="iconfont iconjiahao"></i>
            </el-upload>
            <!-- <a :href="fileAddress">点击下载信息表模板</a> -->
            <a href="http://www.hdtun.com/files/template/contact.xlsx">点击下载信息表模板</a>
          </div>
        </div>
      </div>
    </div>
    <!-- 商品信息 --> 
    <div class="commodity-info">
      <div class="receive-goods-title">
        商品信息
      </div>
      <div class="commodity-cart-item">
        <!-- 标题 -->
        <div class="commodity-title">
          <div class="commodity-left title">
            商品
          </div>
          <div class="commodity-right">
            <div class="w">单价</div>
            <div class="w">数量</div>
            <div class="w">小计</div>
            <div class="w">操作</div>
          </div>
        </div>
        <!-- 图文列表 -->
        <!-- <template v-if="lists.length"> -->
          <div class="commodity-img-txt">
            <div class="commodity-left img-txt">
              <nuxt-link class="img-box" to="/pickGoodsHall">
                <img  alt="" v-lazy="lists.skuImage" :key="lists.skuImage">
              </nuxt-link>
              <div class="text">{{lists.skuName}}</div>
            </div>
            <div class="commodity-right set-count">
              <div class="w commodity-price">￥ {{filterNum(lists.ratePrice)}}</div>
              <div class="w commodity-num">{{lists.count}}</div>
              <div class="w commodity-count">
                <div class="commodity-calc" :class="{'active':borderFlag===true}">
                  <div class="reduce"  @click="reduce()" :class="{'active1':lists.count==1}" @mouseenter="borderFlag=true" @mouseleave="borderFlag=false"></div>
                  <div class="count" :title="lists.count"><input type="text" v-model="lists.count" @input="iptNumber"></div>
                  <div class="plus" @click="plus()"  @mouseenter="borderFlag=true" @mouseleave="borderFlag=false"></div>
                </div>
              </div>
              <div class="w commodity-delete">
                <div class="delete-btn" @click="del(index)">删除</div>
              </div>
            </div>
          </div>
        <!-- </template> -->
        <!-- 暂无商品信息 -->
        <!-- <div class="no-wrap" v-else>暂无商品信息哦!</div> -->
      </div>
      <!-- 去付款 -->
      <div class="to-payment">
        <div class="total-price">
          应付总额: <p>￥{{totalPrice}}</p>
        </div>
        <div class="payment-btn" @click="toPayment">
          去付款
        </div>
      </div>
    </div>
    <!-- 支付弹窗 -->
    <div class="mask" v-show="payFlag">
      <div class="payment-modal">
        <div class="header">
          <p>支付方式</p>
          <i class="iconfont iconerror4" @click="closePopup"></i>
        </div>
        <div class="content">
          <!-- 支付平台 -->
          <div class="platform-payment">
            <div class="weixin-payment" :class="{'active':n===2}" @click="clickHandler(2)" >
              <div class="center-logo">
                <img src="../assets/images/weixin-logo.png" alt="加载中...">
                <p>微信支付</p>
              </div>
              <div class="center-price">{{totalPrice}} <span>元</span></div>
              <div class="triangle-wrapper" v-show="n===2">
                <div class="triangle-tick"></div>
                <i class="iconfont iconduihao1"></i>
              </div>
            </div>
            <div class="zhifubao-payment" :class="{'active':n===1}" @click="clickHandler(1)">
              <div class="center-logo">
                <img src="../assets/images/zhifubao-logo.png" alt="">
                <p>支付宝支付</p>
              </div>
              <div class="center-price">{{totalPrice}} <span>元</span></div>
              <div class="triangle-wrapper" v-show="n===1">
                <div class="triangle-tick"></div>
                <i class="iconfont iconduihao1"></i>
              </div>  
            </div>
          </div>
          <!-- 微信付二维码 -->
          <div class="payment-qrcode" v-if="n===2">
            <div class="plat-payment">
              <img src="../assets/images/weixin-small-logo.png" alt="">
              <p>微信支付</p>
            </div>
            <div class="qr-code">
              <!-- <img src="../assets/images/qr-code.png" alt=""> -->
              <img :src="qrCodeImg" alt="">
              <div class="scan-code-payment">
                微信扫码支付 <span>{{totalPrice}}</span> 元
              </div>
            </div>
          </div>
          <!-- 支付宝支付二维码 -->
          <div class="payment-qrcode" v-else>
            <div class="plat-payment">
              <img src="../assets/images/zhifubao-logo.png" alt="">
              <p>支付宝支付</p>
            </div>
            <div class="qr-code">
              <img :src="qrCodeImg" alt="">
              <div class="scan-code-payment">
                支付宝扫码支付 <span>{{totalPrice}}</span> 元
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  async fetch({store}){
    await store.commit('setInterIndex',3)
  },
  layout: 'internalouts',
  data () {
    return{
      //页面加载
      loading:false,
      //存放上传的文件列表
      fileList:[],
      //图文列表数据
      lists:{},
      count:1,
      payFlag:false,
      n:2, //2代表的是微信 1代表的是支付宝
      borderFlag:false,
      //控制message 弹框重复弹出
      test:'',
      //用户姓名
      username:'',
      //用户手机
      usermobile:'',
      //商品图片
      commodityImg:'',
      //商品数量
      commodityCount:Number,
      //商品折扣价
      commodityDiscount:'',
      //商品名称
      commodityName :'',
      //文件上传的地址
      fileAddress:`${process.env.APIHOST}/common/fileUpload`,
      //文件上传添加token
      headers: {
				token: ''
      },
      orderId:Number,
      //支付二维码
      qrCodeImg:"",
      //定时器模仿websocket即时通信
      timer:null,
      // 支付成功
      payStatus:null
    }
  },
  mounted(){
    this.headers.token = localStorage.getItem('token') ? localStorage.getItem('token') : '';
    let goodsId = this.$route.query.goodsId
    if(!goodsId){
      this.loading = true;
    }else{
      //初始化页面，传递goodsId
      this.placeOrderInfo(goodsId); 
    }
  },
  beforeDestroy(){
    clearInterval(this.timer);
    this.timer = null;
  },
  destroyed(){
    clearInterval(this.timer);
    this.timer = null;
  },
  computed:{
    // 总价
    totalPrice(){
      let parseCount = parseFloat(Number(this.lists.count)*Number(this.lists.ratePrice)).toFixed(2);
      return this.lists ? parseCount :'0'
    },
    //保留小数两位
    filterNum(){ 
      return  function(price){
        //  解决js二进制问题
        return parseFloat(Number(price)).toFixed(2)
      }
    },
    // 监听价格
    count() {
      if( this.lists.count < 0){
        return this.$set(this.lists,count,"0")
      }
    }
  },
  watch:{
    lists(newVal,oldVal){
      console.log(newVal)
      //拿到商品图片
      this.commodityImg = newVal.skuImage;
      //拿到商品名称
      this.commodityName = newVal.skuName;
      //拿到折扣价
      this.commodityDiscount = newVal.ratePrice;
    },
    payStatus(){ 
      if(this.payStatus === "1"){
        clearInterval(this.timer);
        this.timer  = null;
        this.$message.success('支付成功');
        //支付成功跳转到我的团单
        this.$router.push('/pickGoodsHall/myorder')
      }
    }
  },
  methods:{
    // 监控输入框中的值
    iptNumber () {
      console.log('变化')
      if( this.lists.count < 1){
        this.lists.count = 1;
      }
    },
    //点击微信和支付宝
    clickHandler(index){
      this.n = index;
      if(this.timer){
        clearInterval(this.timer);
        this.timer = null;
      }else {
        this.toPayment();
        // this.paymentQrCode(this.orderId,this.n)
      }
      // this.paymentQrCode(this.orderId,this.n)
      this.toPayment();
    },
    // 下单商品信息
    placeOrderInfo(goodsId){
      this.loading = true;
      let params = {
        goodsId:goodsId
      }
      this.$axios.$post('placeOrderInfo',params).then(res => {
        this.loading = false;
        if(res.status === 200){
          console.log(res)
         this.$set( res.obj, "count", "1" )
          // res.obj.count = "1"/
         this.lists = res.obj;
        }else{
          this.$message.warning(res.msg);
        }
      })
      .catch(error => {
        this.$message.warning('请求失败');
        this.loading = false;
      })
    },
    //下单三步走
    async toPayment(){
      //没有输入用户信息我们就不让弹出支付框
      if(!this.username && !this.mobile) return this.$message.warning("请输入联系人信息")
      if(this.fileList.length === 0) return this.$message.warning("请上传文件")
        let  params = {
          //用户姓名
          contactName:this.username,
          //用户手机号码
          contactMobile:this.usermobile,
          //商品图片
          imageUrl:this.commodityImg,
          //商品数量
          amount:this.lists.count,
          //商品折扣价
          goodsPrice:Number(this.commodityDiscount),
          //商品名称
          goodsName:this.commodityName,
          //商品总价
          sumMoney:this.totalPrice,
          //上传的文件信息
          contactAttach:this.fileList[0].url,
          //商品ID
          goodsId:this.lists.id,
          //支付二维码
          QrCodeImg:"",
        }
        //第一步:去下单 
        this.orderId = await this.placeOrder(params);
        this.payFlag =true;
        //第二步:支付二维码  //拿到支付二维码
        this.qrCodeImg  = await this.paymentQrCode(this.orderId,this.n);
        // 每次调用前，如果有定时器，先清除定时器
        if(this.timer){
          clearInterval(this.timer);
          this.timer = null;
        }else{
          //第三步 验证是否付款成功
          this.timer = setInterval (()=>{
            this.validatePayment(this.orderId)
          },2000)
        }
    },
    //第一步:去下单 
    placeOrder(params){
      return new Promise((resolve,reject)=>{
        this.$axios.$post('placeOrder',params).then(res => {
          this.loading = false;
          if(res.status === 200){
            // console.log(res)
            resolve(res.obj.orderId)
          }else{
            this.$message.warning(res.msg);
          }
        })
        .catch(error => {
          this.$message.warning('请求失败');
          this.loading = false;
          reject(error)
        })
      })
    },
    //第二步:支付二维码
    paymentQrCode(orderId,tradType){
      return new Promise((resolve,reject)=>{
        this.$axios.$post('paymentQrCode',
        {orderId:orderId,tradType:tradType},
      ).then(res => {
          this.loading = false;
          if(res.status === 200){
            resolve(res.msg)
          }else{
            this.$message.warning(res.msg);
          }
        })
        .catch(error => {
          this.$message.warning('请求失败');
          this.loading = false;
          reject(error)
        })
      })
    },
    //第三步 验证是否付款成功
    validatePayment(orderId){
      this.$axios.$post('validatePayment',
        {orderId:orderId},
      ).then(res => {
          this.loading = false;
          if(res.status === 200){
            // console.log('验证是否付款成功',res)
            this.payStatus = res.obj.payStatus;
            if(this.payStatus === "1"){
              clearInterval(this.timer);
              this.timer  = null;
              this.$message.success('支付成功');
              //支付成功跳转到我的团单
              this.$router.push('/pickGoodsHall/myorder')
            }
          }
        })
      // })
    },
    //添加文件/上传成功和上传失败都会被调用
    handleChange(file, fileList){
      console.log('fileChange',file)
      console.log('fileList',fileList)
    },
    //上传文件前验证,只能上传者两种格式
    beforeFileUpload(file) {
      let Xls = file.name.split('.'); 
      if(Xls[1] === 'xls'||Xls[1] === 'xlsx'){
        return file
      }else {
        this.$message.error('上传文件只能是 xls/xlsx 格式!')
        return false
      }
    },
    //文件上传成功 没用
    uploadFileSuccess(response,file){
      let fileObj = {
				status: file.status,
				uid: file.uid,
        url: response.obj,
        name:file.name,
			}
			this.fileList.push(fileObj)
    },
    //文件上传失败
    handleFileFail(response,file){
      console.log(response,file)
    },
    // 文件删除
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    //购物车加号事件
    plus(){
      this.lists.count = Number(this.lists.count) + Number(1);
      this.commodityCount = this.lists.count;
    },
    //购物车减号事件
    reduce(){
      if(Number( this.lists.count)>1){
         this.lists.count = Number(this.lists.count)-Number(1);
      }else{
        this.borderFlag =false;
      }
    },
    //删除事件
    del(index){
      this.$router.push('/pickGoodsHall');
    },
    //关闭弹窗
    closePopup(){
      //清除定时器
      if(this.timer){
        clearInterval(this.timer);
        this.timer = null;
      }else{
        this.payFlag = false;
      }
    },
  },
}
</script>

<style scoped>
  .place-order-wrapper{
    width:1200px;
    margin:0 auto;
    margin-top:20px;
  }
  .receive-goods-info{
    overflow:hidden;
    padding-bottom:50px;
    background-color: #ffffff;
    border-radius:4px;
  }
  .receive-goods-title{
    display:inline-block;
    width:88px;
    height:18px;
    margin:30px 0 12px 60px;
    border-left:4px solid #0096e6;
    box-sizing:border-box;
    text-align:right;
    letter-spacing:1px;
    font-size: 14px;
    font-weight:bold;
    line-height:1.2;
  }
  .receive-goods-ipt{
    margin-left:90px;
  }
  .ipt-item{
    display:flex;
    width:504px;
    height:30px;
    align-items:center;
    justify-content: flex-end;
    margin-top:18px;
  }
  .ipt-upload{
    display:flex;
    justify-content: flex-start;
    height:auto;
    width:504px;
    margin-top:18px;
  }
  .ipt-item .left,
  .ipt-upload .left{
    white-space: nowrap;
    margin-right:12px;
  }
  .ipt-upload .left{
    margin-top:10px;
  }
  .ipt-item .right,
  .ipt-upload .right{
    width:355px;
    height:30px;
    border:1px solid #e1e1e1;
    box-sizing: border-box;
    padding-left:12px;
    border-radius:6px;
  }
  .ipt-upload .right{height:auto}
  .ipt-item .right:focus{
    border:1px solid #0096e6;
}
  /* 文件上传 */
  .upload{
    position: relative;
    margin-left: 3px;
  }
  .upload /deep/ .el-button--small{
    padding:7px 14px 7px 34px;
    color:#ffffff;
    background-color: #0096e6;
    font-size:14px;
  }
  .upload /deep/ .el-button--small:hover{
  background-color: #66B1FF;
  }
  .upload i{
    position: absolute;
    left: 14px;
    top: 9px;
    font-size: 12px;
    color: #ffffff;
  }
  .upload a{
    position: absolute;
    white-space: nowrap;
    top: 7px;
    left: 133px;
    font-size: 16px;
    color: #0096e6;
  }
  .upload a:hover{
    color: #66B1FF;
  }
  /* 商品信息 */
  .commodity-info{
    margin-top:20px;
    background-color: #ffffff;
    padding-bottom:50px;
  }
  .commodity-cart-item{
    width:1060px;
    border:1px solid #e1e1e1;
    box-sizing:border-box;
    margin:18px 60px 0px 90px;
  }
  /* 标题 */
  .commodity-title{
    display:flex;
    height:30px;
    line-height:30px;
    align-items:center;
    justify-content:space-between;
    background-color: #f8f9fb;
  }
  .commodity-left{
    width:570px;
  }
  .commodity-title .title{
    height:30px;
    padding-left:60px;
    box-sizing:border-box;
}
  /* 图文列表 */
  .commodity-img-txt{
    display:flex;
    padding:20px 0;
    box-sizing: border-box;
  }
  .commodity-img-txt:nth-child(odd){
    background-color: #f8f9fb;
  }
  .commodity-img-txt .img-txt{
    display:flex;
    padding-left: 20px;
    box-sizing: border-box;
  }
  .img-txt .img-box{
    width: 113px;
    height: 113px;
    flex-shrink:0;
  }
  .img-txt .img-box img{
    display:block;
    width: 100%;
    height: 100%;
  }
  .commodity-left .text{
    font-size: 14px;
    margin-top:20px;
    margin-left:30px;
    display:-webkit-box;
    -webkit-box-orient:vertical;
    -webkit-line-clamp:3;
    text-overflow:ellipsis;
    overflow:hidden;
    line-height:1.3;
  }
  .commodity-right{
    width:490px;
    display:flex;
    text-align: center;
    height:30px;
  }
  .commodity-right .w{
    width:25%;
  }
  .commodity-price{
    color:#e01222;
  }
  /* 计算器 */
  .set-count {
    align-items:center;
    margin-top:14px;
  }
  .commodity-calc{
    width:108px;
    height:24px;
    display:flex;
    align-items:center;
    line-height:24px;
    border:1px solid #e1e1e1;
    box-sizing:border-box;
    margin:0 auto;
  }
  .commodity-count .active{
    border:1px solid #0096e6;
    color:#0096e6;
  }
  .commodity-calc .active1{
    pointer-events: none;
  }
  .reduce,
  .plus{
    width:30px;
    height:24px;
    cursor:pointer;
    position: relative;
    user-select:none;
  }
  .plus::before,
  .reduce::before{
    content: '';
    position: absolute;
    left: 50%;
    top: 50%;
    width: 12px;
    margin-left: -6px;
    border-top: 2px solid #666666;
  }
  .plus::after {
    content: '';
    position: absolute;
    left: 50%;
    top: 50%;
    height: 12.5px;
    margin-left: -1px;
    margin-top: -5px;
    border-left: 2px solid #666666;
  }
  .reduce{
    border-right:1px solid #e1e1e1;
  }
  .plus{
    border-left:1px solid #e1e1e1;
  }
  .count{
    width:60px;
    height:24px;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
  .count input {
    width: 100%;
    height: 100%;
    padding: 0 20px;
  }
  .delete-btn{
    width:70px;
    height:30px;
    line-height: 30px;
    text-align: center;
    color:#0096e6;
    background-color: #f0f9fe;
    margin:0 auto;
    border-radius:15px;
    cursor:pointer;
    user-select:none;
    letter-spacing:1px;
  }
  .commodity-delete .active{
    color:#ffffff;
    background-color: #0096e6;
  }
  .delete-btn:hover{
    color:#ffffff;
    background-color: #0096e6;
  }
  .to-payment{
    height:60px;
    line-height: 60px;
    text-align: center;
    background-color: #f8f9fb;
    display:flex;
    justify-content:flex-end;
    border:1px solid #e1e1e1;
    box-sizing:border-box;
    margin: 20px 47px 0 90px;
  }
  .total-price{
    margin-right:30px;
    font-size: 16px;
    display:flex;
    align-items:center;
  }
  .total-price p{
    font-size: 24px;
    color:#e01222;
    font-weight:bold;
  }
  .payment-btn{
    width: 160px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    background-color: #0096e6;
    color:#ffffff;
    letter-spacing:1px;
    cursor:pointer;
    font-size: 20px;
    user-select:none;
  }
  .payment-btn:hover{
    background-color:#66B1FF;
  }
  /* 暂无数据 */
  .no-wrap{
    height:60px;
    line-height: 60px;
    text-align:center;
    font-size: 14px;
    color: #909399;
    margin-bottom:20px;
    letter-spacing:1px;
  }
  /* 支付模态框*/
  .mask{
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    background-color:rgba(0,0,0,0.5);
    z-index:99999;
  }
  .payment-modal{
    width:620px;
    height:450px;
    position:absolute;
    top:50%;
    left:50%;
    transform:translate(-50%,-50%);
    border-radius:4px;
    background-color: #fff;
    padding-bottom:36px;
  }
  .header{
    display:flex;
    justify-content:space-between;
    height:50px;
    line-height: 50px;
    background-color: #0096e6;
    color:#ffffff;
    font-size:18px;
    padding:0 20px;
  }
  .header i{
    font-size:24px;
    cursor:pointer;
  }
  .content{
    margin:36px 60px 0;
    width:500px;
  }
  /*支付平台  */
  .platform-payment{
    display:flex;
    justify-content:space-between;
    align-items:center;
  }
  .weixin-payment,
  .zhifubao-payment{
    width:240px;
    border:1px solid #e1e1e1;
    box-sizing:border-box;
    border-radius:4px;
    padding:40px 50px;
    position:relative;
    cursor:pointer;
  }
  .platform-payment .active{
    border:2px solid #0096e6;
    box-sizing:border-box;
  }
  .center-logo{
    display:flex;
    height:30px;
    line-height:30px;
    align-items:center;
    letter-spacing:1.5px;
    font-size:18px;
    white-space:nowrap;
  }
  .center-logo img{
    width: 30px;
    height: 27px;
    display:block;
    margin-right:14px;
  }
  .center-price{
    font-size:18px;
    height:40px;
    line-height: 40px;
    letter-spacing:1.5px;
    text-align:right;
    color:#0096e6; 
  }
  .center-price span{
    color:#b6b6b6;
  }
  .triangle-wrapper{
    position: absolute;
    bottom: -28px;
    right: -27px;
  }
  .triangle-tick{
    width:0;
    height:0;
    border:26px solid;
    border-color:transparent transparent transparent #0096e6;
    transform:rotate(45deg);
  }
  .triangle-wrapper i{
    color: #fff;
    font-size: 26px;
    position: absolute;
    right: 26px;
    bottom: 22px;
  }
  /*支付二维码  */
  .payment-qrcode{
    margin:20px 0 0;
    height:185px;
    border-radius:4px;
    border:1px solid #e1e1e1;
  }
  .plat-payment{
    height:30px;
    line-height:30px;
    display:flex;
    align-items:center;
    font-size:12px;
    padding-left:12px;
  }
  .plat-payment img{
    margin-right:10px;
  }
  .qr-code{
    height:145px;
    display:flex;
    align-items:center;
    padding:0 0 20px 40px;
  }
  .qr-code img{
    display:block;
    width:133px;
    height:133px;
    margin-right:54px;
    font-size:16px;
  }
  .scan-code-payment span{
    color:#0096e6;
  }
</style>
